import { defineStore } from "pinia";
import { componentDefaultConfig as defaultConfig } from "@/configs/codeBuilderCompMap";
import { dispatchUpdateComponentConfig } from "./actions";

let compId = 1; // 组件ID

// 组件默认配置（目前只有选项 均为options）
const componentDefaultConfig = {};
for (const key in defaultConfig) {
  componentDefaultConfig[key] = defaultConfig[key];
}

export const useCodeBuilderState = defineStore("CodeBuilder", {
  state: () => ({
    componentDefaultConfig,
    currentComp: null,
    componentList: [],
  }),
  actions: {
    dispatchUpdateComponentConfig,
    // 设置当前组件
    setCurrentComp(comp) {
      this.currentComp = comp;
    },
    normalizeComp(comp) {
      comp.id = compId++;
      if (comp.isBlock && !comp.children) {
        comp.children = []; // Initialize children for block components
      }
      return comp;
    },
    // 添加组件
    addComponent(comp) {
      this.normalizeComp(comp);
      if (this.currentComp?.isBlock && !comp.isBlock) {
        this.currentComp.children.push(comp);
      } else {
        this.componentList.push(comp);
      }
      return comp.id;
    },
    // 删除组件
    removeComponent(id) {
      return findComponent(this.componentList, id, (comp, index, list) => {
        list.splice(index, 1);
        if (comp.id === this.currentComp?.id) {
          this.currentComp = null;
        }
      });
    },
    // 更新组件列表
    setComponents(components) {
      console.log(components);
      // this.componentList = components;
    },
    updateCompState(id, state) {
      return findComponent(this.componentList, id, (comp) => {
        comp = Object.assign(comp.state, state);
      });
    },
  },
});

function findComponent(components, id, cb) {
  const index = components.findIndex((item) => item.id === id);
  if (index > -1) {
    cb(components[index], index, components);
    return;
  }
  for (const comp of components) {
    if (comp.children) {
      findComponent(comp.children, id, cb);
    }
  }
}
